package com.syzg.view.tags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.syzg.common.model.WebObj;
import com.syzg.core.page.PageResult;
import com.syzg.core.util.StringUtil;

public class TableTag extends SimpleTagSupport {
	
	private String id;
    private String value;
    private String caption;
    private String cssClass;
    private String cssStyle;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	public String getCssClass() {
		return cssClass;
	}

	public void setCssClass(String cssClass) {
		this.cssClass = cssClass;
	}

	public String getCssStyle() {
		return cssStyle;
	}

	public void setCssStyle(String cssStyle) {
		this.cssStyle = cssStyle;
	}

	@Override
	public void doTag() throws JspException, IOException {
		
		JspWriter out = this.getJspContext().getOut();
		PageContext pageContext = (PageContext)getJspContext();
		List<Object> items = null;
		if(StringUtil.isNotEmpty(value)){
			items = (List<Object>)pageContext.getRequest().getAttribute(value);
		} else {
			WebObj webObj = (WebObj)pageContext.getRequest().getAttribute("webObj");
			items = (List<Object>)webObj.getPageResult().getItems();
		}
		
		if(items == null)items = new ArrayList<Object>();
		
		this.getJspContext().setAttribute("headFlag", "true");
		StringBuffer sb = new StringBuffer();
		sb.append("<table id=\"" + id + "\" width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"");
		if(StringUtil.isNotEmpty(cssClass)){
			sb.append(" class=\"" + cssClass + "\"");
		} else {
			sb.append(" class=\"list\"");
		}
		if(StringUtil.isNotEmpty(cssStyle)){
			sb.append(" style=\"" + cssStyle + "\"");
		}
		if(StringUtil.isNotEmpty(caption)){
			sb.append(" title=\"" + caption + "\"");
		}
		sb.append(">");
		out.println(sb.toString());
		JspFragment jf = this.getJspBody();
		out.print("<thead>");
		out.print("<tr height=\"20px;\">");
		jf.invoke(out);
		out.print("</tr>");
		out.print("</thead>");
		this.getJspContext().setAttribute("headFlag", "false");
		out.print("<tbody>");
		for(int i=0;i<items.size();i++){
			Object obj = items.get(i);
			this.getJspContext().setAttribute("o", obj);
			
			if(i%2==0){
				out.print("<tr height=\"15px;\">");
			} else {
				out.print("<tr height=\"15px;\">");
			}
			jf.invoke(out);
			out.print("</tr>");
		}
		out.print("</tbody>");
		out.println("</table>");
	}
	
}
